package com.ma.chapter4.t2;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "m.test")
public class TestShareCount {
    public static int count = 0;
    //阻塞式解决方案
    public static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.increment();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.decrement();
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("count = {}", count);


    }
}


class Room{
    private int count;

    /**
     * synchronized加在方法上，锁住的式this对象
     * synchronized加在静态方法上，锁住的是类对象
     */

    public synchronized void increment(){
        count++;
    }
    public synchronized void  decrement(){
        count--;
    }

    public int get(){
        return count;
    }
}